/**
 * Filename: ItemDragHelperCallback.java
 * @author  Firefly
 * @contact postfirefly@163.com
 * @time    2016/4/15 16:14
 */
package com.github.postsanf.yinian.inter;

import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;

/**
 * 子项拖拽回调接口
 */
public class ItemDragHelperCallback extends ItemTouchHelper.Callback {

	private final OnItemMoveListener mAdapter;

	public ItemDragHelperCallback(OnItemMoveListener adapter) {
		mAdapter = adapter;
	}

	@Override
	public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
//		int dragFlags;
//		RecyclerView.LayoutManager manager = recyclerView.getLayoutManager();
//		if (manager instanceof GridLayoutManager || manager instanceof StaggeredGridLayoutManager) {
//			dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN | ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT;
//		} else {
//			dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN;
//		}
//		// 如果想支持滑动(删除)操作, swipeFlags = ItemTouchHelper.START | ItemTouchHelper.END
//		int swipeFlags = 0;
//		return makeMovementFlags(dragFlags, swipeFlags);
		int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN | ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT;
//		int swipeFlags = ItemTouchHelper.START | ItemTouchHelper.END;
		return makeMovementFlags(dragFlags, 0);
	}

	@Override
	public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
//		// 不同Type之间不可移动
//		if (viewHolder.getItemViewType() != target.getItemViewType()) {
//			return false;
//		}
//
//		if (recyclerView.getAdapter() instanceof OnItemMoveListener) {
//			OnItemMoveListener listener = ((OnItemMoveListener) recyclerView.getAdapter());
//			listener.onItemMove(viewHolder.getAdapterPosition(), target.getAdapterPosition());
//		}
		mAdapter.onItemMove(viewHolder.getAdapterPosition(), target.getAdapterPosition());

		return true;
	}

	@Override
	public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {}

	@Override
	public void onSelectedChanged(RecyclerView.ViewHolder viewHolder, int actionState) {
		// 不在闲置状态
		if (actionState != ItemTouchHelper.ACTION_STATE_IDLE) {
			if (viewHolder instanceof OnDragVHListener) {
				OnDragVHListener itemViewHolder = (OnDragVHListener) viewHolder;
				itemViewHolder.onItemSelected();
			}
		}
		super.onSelectedChanged(viewHolder, actionState);
	}

	@Override
	public void clearView(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
		if (viewHolder instanceof OnDragVHListener) {
			OnDragVHListener itemViewHolder = (OnDragVHListener) viewHolder;
			itemViewHolder.onItemFinish();
		}
		super.clearView(recyclerView, viewHolder);
	}

	@Override
	public boolean isLongPressDragEnabled() {
		// 长按拖拽功能
		return true;
	}

	@Override
	public boolean isItemViewSwipeEnabled() {
		// 不需要滑动功能
		return false;
	}
}